﻿using PARK.Common.Enum;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.FriendlyException;
using PARK.System.Entitys.Permission;
using PARK.System.Interfaces.Permission;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Threading.Tasks;
using System.Text;
using System.Data;

namespace PARK.System.Service.Permission
{
    /// <summary>
    ///  业务实现：用户信息
    /// </summary>
    [ApiDescriptionSettings(Tag = "Permission", Name = "Users", Order = 163)]
    [Route("api/permission/[controller]")]
    public class UserloginlogService : IUserloginlogService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<UserloginlogEntity> _userRepository;  // 用户表仓储       
        private readonly SqlSugarScope _db;
        private readonly HttpContext _httpContext;

        /// <summary>
        /// 初始化一个<see cref="UserloginlogService"/>类型的新实例
        /// </summary>
        public UserloginlogService(ISqlSugarRepository<UserloginlogEntity> userRepository)
        {
            _userRepository = userRepository;           
            _httpContext = App.HttpContext;
            _db = _userRepository.Context;
        }

        /// <summary>
        /// 日志入库
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [NonAction]
        public async Task Create(UserloginlogEntity input)
        {
            var entity = input;
            try
            {
                entity.Create();
                await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            }
            catch (Exception ex)
            {
                //回滚事务
                _db.RollbackTran();
                throw PARKException.Oh(ErrorCode.COM1000);
            }
        }

        /// <summary>
        /// 验证是否允许登录
        /// </summary>
        /// <param name="account"></param>
        /// <param name="IPAddress"></param>
        /// <returns></returns>
        [NonAction]
        public  bool CheckIsAllowlogin(string account,string IPAddress)
        {
            try
            {
                StringBuilder dbSql = new StringBuilder("select count(0) as ts from base_user_loginlog where isnull(F_LoginRet,0)=0 and  F_LoginTime>=dateadd(HOUR,-24,getdate()) ");
                dbSql.AppendFormat(" and (F_IPAddress='{0}' or F_LoginAccount='{1}')", IPAddress, account);
                var ds = _db.SqlQueryable<DataTable>(dbSql.ToString()).ToDataTable();
                if (ds.Rows.Count > 0)
                {
                    if (int.Parse(ds.Rows[0]["ts"].ToString()) >= 5)
                        return false;
                    else
                        return true;
                }
                else
                    return true;
            }
            catch(Exception ex)
            {
                return false;
            }
        }
    }
}